package cn.iocoder.yudao.module.vote.controller.admin.voteinfo;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import cn.iocoder.yudao.module.vote.controller.admin.userref.vo.VoteUserRefCreateReqVO;
import cn.iocoder.yudao.module.vote.controller.admin.userref.vo.VoteUserRefUpdateReqVO;
import cn.iocoder.yudao.module.vote.convert.userref.VoteUserRefConvert;
import cn.iocoder.yudao.module.vote.service.userref.VoteUserRefService;
import cn.iocoder.yudao.module.vote.service.voterecord.VoteRecordService;
import cn.iocoder.yudao.module.vote.service.voteuserresult.VoteUserResultService;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import oracle.jdbc.proxy.annotation.Post;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.annotations.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.awt.image.BufferedImage;
import java.util.*;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.*;
import static cn.iocoder.yudao.module.vote.enums.ErrorCodeConstants.*;

import cn.iocoder.yudao.module.vote.controller.admin.voteinfo.vo.*;
import cn.iocoder.yudao.module.vote.dal.dataobject.voteinfo.VoteInfoDO;
import cn.iocoder.yudao.module.vote.convert.voteinfo.VoteInfoConvert;
import cn.iocoder.yudao.module.vote.service.voteinfo.VoteInfoService;

@Api(tags = "管理后台 - 投票规则")
@RestController
@RequestMapping("/vote/info")
@Validated
@Slf4j
public class VoteInfoController {

    @Resource
    private VoteInfoService infoService;
    @Resource
    private VoteRecordService voteRecordService;


    @PostMapping("/create")
    @ApiOperation("创建投票规则")
    @PreAuthorize("@ss.hasPermission('vote:info:create')")
    public CommonResult<Integer> createInfo(@Valid @RequestBody VoteInfoCreateReqVO createReqVO) {

        if(createReqVO.getBeginTime().after(createReqVO.getEndTime())){
            throw exception(BEGIN_GT_END_TIME);
        }

        return success(infoService.createInfo(createReqVO));
    }


    @PutMapping("/update")
    @ApiOperation("更新投票规则")
    @PreAuthorize("@ss.hasPermission('vote:info:update')")
    public CommonResult<Boolean> updateInfo(@Valid @RequestBody VoteInfoUpdateReqVO updateReqVO) {

        if(updateReqVO.getBeginTime().after(updateReqVO.getEndTime())){
            throw exception(BEGIN_GT_END_TIME);
        }
        infoService.updateInfo(updateReqVO);
        return success(true);
    }

    @PutMapping("/pushVote")
    @ApiOperation("发布投票规则")
    @PreAuthorize("@ss.hasPermission('vote:info:update')")
    public CommonResult<Boolean> pushVote(@RequestBody VoteInfoUpdateReqVO updateReqVO) {


        infoService.pushState(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @ApiOperation("删除投票规则")
    @ApiImplicitParam(name = "id", value = "编号", required = true, dataTypeClass = Integer.class)
    @PreAuthorize("@ss.hasPermission('vote:info:delete')")
    public CommonResult<Boolean> deleteInfo(@RequestParam("id") Integer id) {
        infoService.deleteInfo(id);
        return success(true);
    }

    @GetMapping("/get")
    @ApiOperation("获得投票规则")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClass = Integer.class)
    @PreAuthorize("@ss.hasPermission('vote:info:query')")
    public CommonResult<VoteInfoRespVO> getInfo(@RequestParam("id") Integer id) {
        VoteInfoDO info = infoService.getInfo(id);
        return success(VoteInfoConvert.INSTANCE.convert(info));
    }

    @GetMapping("/getCurrVote")
    @ApiOperation("获得投票规则")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClass = Integer.class)
    public CommonResult<VoteInfoRespVO> getCurrVote(Integer voteType) {
        voteType = voteType==null?1:2;
        VoteInfoDO info = infoService.getCurrVote(voteType);
        return success(VoteInfoConvert.INSTANCE.convert(info));
    }

    @PostMapping("/getQrCode")
    @ApiOperation("获得二维码")
    public CommonResult<String> getQrCode(@RequestBody OnlineVoteParamsVO paramsVO,HttpServletResponse response) {
        String base64 = infoService.getQrCode(paramsVO);
        return success(base64);
    }


    @GetMapping("/page")
    @ApiOperation("获得投票规则分页")
    @PreAuthorize("@ss.hasPermission('vote:info:query')")
    public CommonResult<PageResult<VoteInfoRespVO>> getInfoPage(@Valid VoteInfoPageReqVO pageVO) {
        PageResult<VoteInfoRespVO> pageResult = VoteInfoConvert.INSTANCE.convertPage(infoService.getInfoPage(pageVO));

        if(CollUtil.isNotEmpty(pageResult.getList())){
            for(VoteInfoRespVO vote :pageResult.getList()){
                vote.setIsVote(voteRecordService.isVote(vote.getId()));
            }
        }

        return success(pageResult);
    }


    @GetMapping("/list-name")
    @ApiOperation("获取列表信息")
    public CommonResult<List<VoteInfoRespVO>> listByName(@Valid VoteInfoPageReqVO pageVO){
        PageResult<VoteInfoDO> list = infoService.getInfoPage(pageVO);
        return success(VoteInfoConvert.INSTANCE.convertList(list.getList()));
    }


    @GetMapping("/list-by-user")
    @ApiOperation("获取列表信息")
    public CommonResult<List<VoteInfoRespVO>> listByUser(@Valid VoteInfoPageReqVO pageVO){
        List<VoteInfoDO> list = infoService.getByUser(pageVO.getVoteType());
        List<VoteInfoRespVO> respVOList =VoteInfoConvert.INSTANCE.convertList(list);

        if (CollUtil.isNotEmpty(respVOList)) {
            for(VoteInfoRespVO respVO:respVOList){
                if(!respVO.getIsQuote()){
                    continue;
                }
                VoteInfoDO prevInfo =  infoService.getInfo(respVO.getQuoteVoteId());
                if(prevInfo!=null){
                    respVO.setPrevVoteName(prevInfo.getVoteName());
                }
            }
        }
        return success(respVOList);
    }

    @PostMapping("/copyVote")
    @ApiOperation("复制投票规则")
    public CommonResult<Boolean> copyVote(VoteInfoUpdateReqVO pageVO){
        if (StrUtil.isBlank(pageVO.getVoteName())) {
            throw  exception(INFO_NAME_NOT_NULL);
        }
        infoService.copyVote(pageVO);
        return success(true);
    }

    @GetMapping("/export-excel")
    @ApiOperation("导出投票规则 Excel")
    @PreAuthorize("@ss.hasPermission('vote:info:export')")
    @OperateLog(type = EXPORT)
    public void exportInfoExcel(@Valid VoteInfoExportReqVO exportReqVO,
              HttpServletResponse response) throws IOException {
        List<VoteInfoDO> list = infoService.getInfoList(exportReqVO);
        // 导出 Excel
        List<VoteInfoExcelVO> datas = VoteInfoConvert.INSTANCE.convertList02(list);
        ExcelUtils.write(response, "投票规则.xls", "数据", VoteInfoExcelVO.class, datas);
    }



}
